import type { Ref } from 'vue'
type WatchElementOptions = {
  el: Ref<Element | undefined>
  className: string
  specifiedClass: string
}

export const useWatchElement = (options: WatchElementOptions) => {
  const observeContainer = () => {
    if (options.el.value) {
      const targetElement = options.el.value.querySelector(
        `.${options.className}`
      )
      if (targetElement) {
        // 如果找到带有特定类的子元素，添加指定的类
        options.el.value?.classList?.add(options.specifiedClass)
      } else {
        options.el.value?.classList?.remove?.(options.specifiedClass)
      }
    }
  }

  const observer = ref()
  // 在组件挂载后执行的代码
  onMounted(async () => {
    await nextTick()
    observeContainer()

    // 使用 MutationObserver 监听容器元素的变化
    observer.value = new MutationObserver(observeContainer)
    observer.value?.observe?.(options.el.value!, {
      childList: true,
      subtree: true
    })
  })

  // 当组件卸载时停止观察
  onBeforeUnmount(() => {
    observer.value?.disconnect?.()
  })
}
